<template>
  <el-upload class="avatar-uploader" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElUpload, ElIcon, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { L12030 } from '../api/L12030'
import { BaseResult } from '../ts/BaseResult'
import { TbFile } from '../ts/File'
import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

const fileinfo = ref({
  info: "用户图片",
})
const urlImg = ref('')
const files = ref(new TbFile())


const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  L12030.upload(fileinfo.value, rawFile, (data: BaseResult) => {
    if (data.success) {
      files.value = data.data
      urlImg.value=L12030.getFileUrl(data.data.fid)
      imageUrl.value = URL.createObjectURL(rawFile)
      const urls = ref({
        img: urlImg.value,
      })
      L12030.put('/userinfo', urls.value, (data: BaseResult) => {
        data.success ? ElMessageBox.alert('修改成功') : ElMessageBox.alert('修改失败')
        location.reload();
      })
    } else {
      ElMessageBox.alert(data.message)
    }
  })
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
